/**
 * 扩展自定义的函数
 */
import { Context } from "egg";
import { globalErrorMessages, GlobalErrorTypes } from "../error";
import { ObjectId } from "mongoose";

interface ResponseType {
  ctx: Context;
  res?: any;
  msg?: string;
}
interface ErrorResponseType {
  ctx: Context;
  errorType: GlobalErrorTypes;
  error?: any;
}

export default {
  success({ ctx, res, msg }: ResponseType) {
    ctx.body = {
      errno: 0,
      ...(res && { data: res }),
      message: msg ? msg : "请求成功！",
    };
    ctx.status = 200;
  },
  error({ ctx, errorType, error }: ErrorResponseType) {
    const { message, errno } = globalErrorMessages[errorType];
    ctx.body = {
      errno,
      message,
      ...(error && { error }),
    };
    ctx.status = 200;
  },
  listToTree<T extends { _id?: ObjectId; parent_id: ObjectId; children: T[] }>(
    list: T[],
    parent_id
  ): T[] {
    const tree = [];
    for (const node of list) {
      if (node.parent_id.toString() === parent_id.toString()) {
        // 递归
        const children = this.listToTree(list, node._id);
        if (children.length) {
          node.children = children;
        }
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        tree.push(node);
      }
    }
    return tree;
  },
};
